package com.kingyea.mobilepolice.apimanage.system.sync;

import com.carrotsearch.sizeof.RamUsageEstimator;
import com.kingyea.mobilepolice.apimanage.provider.bean.Provider;
import com.kingyea.mobilepolice.apimanage.provider.service.ProviderService;
import com.kingyea.mobilepolice.apimanage.requester.bean.Requester;
import com.kingyea.mobilepolice.apimanage.requester.service.RequesterService;
import com.kingyea.mobilepolice.apimanage.serverapimonitor.bean.ServerApiMonitor;
import com.kingyea.mobilepolice.apimanage.serverapimonitor.service.ServerApiMonitorService;
import com.kingyea.mobilepolice.apimanage.serviceinfo.bean.ServiceInfo;
import com.kingyea.mobilepolice.apimanage.serviceinfo.service.ServiceInfoService;
import com.kingyea.mobilepolice.apimanage.sysvo.bean.RequestObj;
import com.kingyea.mobilepolice.apimanage.utils.GlobalVar;
import com.kingyea.mobilepolice.apimanage.utils.NumberUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.Optional;

/**
 * @author cxc
 * @version v1.0.0
 * @description
 * @date Created in 2018/5/19 15:43
 */
@Component
public class ServerApiMonitorTask {

    private static final Logger LOGGER = LoggerFactory.getLogger(InterfaceFlowTask.class);

    @Autowired
    private ServerApiMonitorService serverApiMonitorService;

    @Autowired
    private ServiceInfoService serviceInfoService;

    @Autowired
    private ProviderService providerService;

    @Autowired
    private RequesterService requesterService;

    /**
     * @Description: 服务接口监控
     * @param: []
     * @return: void
     * @author: cxc
     * @Date: 2018/5/19
     */
    @Async
    public void saveMonitor(long startTime, RequestObj requestObj, Object result, HttpServletRequest request) {
        try {
            //上行数据大小
            ServerApiMonitor monitor = new ServerApiMonitor();
            monitor.setUploadBytes(Long.valueOf(RamUsageEstimator.sizeOf(requestObj.getParams())).intValue());
            monitor.setUploadPkg(1);//一个包够了吧
            //下行数据大小
            monitor.setDownloadBytes(Long.valueOf(RamUsageEstimator.sizeOf(result)).intValue());
            monitor.setDownloadPkg(1);
            //源端ip port
            monitor.setSrcIp(getRemoteAddress(request));
            monitor.setSrcPort(request.getRemotePort());
            //服务端ip port
            ServiceInfo serviceInfo = serviceInfoService.getBySerialNo(requestObj.getServiceSN());
            boolean serviceInfoIsNotNull = true;
            if(null==serviceInfo||NumberUtils.isLEZeroNumObj(serviceInfo.getId())){
                serviceInfoIsNotNull = false;
            }
            if(serviceInfoIsNotNull){
                monitor.setDstIp(serviceInfo.getServiceAddress());
                monitor.setDstPort(Optional.ofNullable(serviceInfo.getPort()).map(Integer::parseInt).orElse(-1));
            }
            //服务信息
            monitor.setServiceSerialNo(requestObj.getServiceSN());
            if(serviceInfoIsNotNull){
                monitor.setAppNames(serviceInfo.getName());
                //提供者信息
                Provider provider = providerService.getById(serviceInfo.getProviderId());
                monitor.setProviderSerialNo(provider.getSerialNo());
                monitor.setProviderName(provider.getProvider());
            }

            //请求者信息
            boolean requesterIsNotNull = true;
            Requester requester = requesterService.getById(requestObj.getRequestId());
            if(null==requester||NumberUtils.isLEZeroNumObj(requester.getId())){
                requesterIsNotNull = false;
            }
            if(requesterIsNotNull){
                monitor.setRequesterSerialNo(requester.getSerialNo());
                monitor.setRequesterName(requester.getRequester());
            }
            //
            if(serviceInfoIsNotNull){
                monitor.setAppProtocal(serviceInfo.getProtocol());
            }
            monitor.setDeviceId(null);
            monitor.setDeviceToken(request.getParameter(GlobalVar.ACCESS_TOKENNAME));
            monitor.setEpochTime(new Date(startTime));
            monitor.setEndTime(new Date());
            monitor.setStartTime(monitor.getEpochTime());
            monitor.setPayLoad(-1);
            monitor.setTransferProtocol(159);//字典表159 http
            assert serverApiMonitorService.save(monitor);
            LOGGER.info("【服务接口监控记录保存完成】");
        } catch (Exception e) {
            //不处理
            LOGGER.error("【服务接口监控记录保存异常】", e);
        }
    }

    public String getRemoteAddress(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || ip.equalsIgnoreCase("unknown")) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || ip.equalsIgnoreCase("unknown")) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || ip.equalsIgnoreCase("unknown")) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }
}
